package ${package}.dao.intercept;

import java.time.LocalDateTime;
import java.util.Properties;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

import ${package}.base.BaseEntity;

@Component
@Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }) })
public class EntityDefaultValueSetter implements Interceptor {

	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		MappedStatement ms = (MappedStatement)invocation.getArgs()[0];
		Object param = invocation.getArgs()[1];
		if (param instanceof BaseEntity) {
			if (ms.getSqlCommandType() == SqlCommandType.INSERT) {
				BaseEntity baseEntity = (BaseEntity)param;
				LocalDateTime now = LocalDateTime.now();
				baseEntity.setCreatedTime(now);
				baseEntity.setUpdatedTime(now);
				baseEntity.setCreator(0L);
				baseEntity.setUpdater(0L);
			}
			else if (ms.getSqlCommandType() == SqlCommandType.UPDATE) {
				BaseEntity baseEntity = (BaseEntity)param;
				LocalDateTime now = LocalDateTime.now();
				baseEntity.setUpdatedTime(now);
				baseEntity.setUpdater(0L);
			}
		}
		return invocation.proceed();
	}

	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	@Override
	public void setProperties(Properties properties) {
		System.out.println("setProperties");
	}

}
